package com.service;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import androidx.annotation.Nullable;

import com.myapp.MyApp;
import com.notifation.DefaultNotifyBuilder;
import com.notifation.NotifyManager;
import com.util.InfoEventMessage;
import com.util.MyLog;
import com.util.RequestManager;
import com.xiaochun.hxhj.MainActivity;
import com.xiaochun.hxhj.R;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.HashMap;

import static org.greenrobot.eventbus.EventBus.TAG;

public class DeviceService extends Service {

    private Handler handlerdelay;
    private SharedPreferences sharedPreferences;
    private boolean isRequest = true;
    private AssistServiceConnection mConnection;

    @Override
    public void onCreate() {
        handlerdelay = new Handler();
        sharedPreferences = getSharedPreferences("userinfo", Activity.MODE_PRIVATE);
        MyLog.e("开启服务","onCreate()");

        setForeground();



        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String device_time = MyApp.device_time;
        if ("".equals(device_time)){
            device_time = "3000";
        }
        final String devicetime = device_time;
        MyLog.e("开启服务","onStartCommand()   间隔时长"+device_time);
        handlerdelay.postDelayed(new Runnable() {
            @Override
            public void run() {
//                MyLog.e("服务执行定时任务","服务执行定时任务");
                String token = sharedPreferences.getString("token", "");
                if (!"".equals(token) && isRequest){
                    getData();
                }
                handlerdelay.postDelayed(this, Integer.parseInt(devicetime));


            }
        },Integer.parseInt(devicetime));


        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    private final int PID = android.os.Process.myPid();
    public void setForeground() {
        // sdk < 18 , 直接调用startForeground即可,不会在通知栏创建通知
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            //Android8以上
            if (null == mConnection) {
                mConnection = new AssistServiceConnection();
            }
        }else{
            //Android8以下
            this.startForeground(PID, getNotification());
        }

        this.bindService(new Intent(this, AssistService.class), mConnection,
                Service.BIND_AUTO_CREATE);
    }
    private class AssistServiceConnection implements ServiceConnection {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "MyService: onServiceDisconnected");
        }
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            Log.d(TAG, "MyService: onServiceConnected");
            // sdk >=18
            // 的，会在通知栏显示service正在运行，这里不要让用户感知，所以这里的实现方式是利用2个同进程的service，利用相同的notificationID，
            // 2个service分别startForeground，然后只在1个service里stopForeground，这样即可去掉通知栏的显示
            Service assistService = ((AssistService.LocalBinder) binder)
                    .getService();
            DeviceService.this.startForeground(PID, getNotification());
            assistService.startForeground(PID, getNotification());
            assistService.stopForeground(true);

            DeviceService.this.unbindService(mConnection);
            mConnection = null;
        }
    }

    private Notification getNotification() {
        // 定义一个notification
//        Notification notification = new Notification();
//        Intent notificationIntent = new Intent(this, MainActivity.class);
//        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
//                notificationIntent, 0);
//        notification.setLatestEventInfo(this, "My title", "My content",
//                pendingIntent);

        Notification notification = new Notification.Builder(this)
                .setContentTitle("主服务")//设置标题
                .setContentText("运行中...")//设置内容
                .setWhen(System.currentTimeMillis())//设置创建时间
                .setSmallIcon(R.mipmap.ic_launcher)//设置状态栏图标
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))//设置通知栏图标
                .build();
//        startForeground(1,notification);


        return notification;
    }
    private Notification getNotification2(){
        Notification notification = null;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel Channel = new NotificationChannel("111","主服务",NotificationManager.IMPORTANCE_HIGH);
            Channel.enableLights(true);//设置提示灯
            Channel.setLightColor(Color.RED);//设置提示灯颜色
            Channel.setShowBadge(true);//显示logo
            Channel.setDescription("ytzn");//设置描述
            Channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); //设置锁屏可见 VISIBILITY_PUBLIC=可见
            manager.createNotificationChannel(Channel);

            notification = new Notification.Builder(this)
                    .setChannelId("111")
                    .setContentTitle("主服务")//标题
                    .setContentText("运行中...")//内容
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.ic_launcher)//小图标一定需要设置,否则会报错(如果不设置它启动服务前台化不会报错,但是你会发现这个通知不会启动),如果是普通通知,不设置必然报错
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                    .build();

        }
        return notification;
    }




    private void getData() {
        String url = MyApp.siteurl + "/api/index/config";
        HashMap<String, String> paramsMap = new HashMap<>();
        RequestManager.getInstance(this).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
//                MyLog.e("服务定时请求任务", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
//                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                    String pay_status = data.getString("pay_status");
                    if (!pay_status.equals(MyApp.deviceId)){
                        EventBus.getDefault().post(new InfoEventMessage("设备ID已更新退出登录"));
                        isRequest = false;
//                        handlerdelay.removeCallbacksAndMessages(null);
                    }else{
                        isRequest = true;
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                }
            }
        });
    }




}